//
//  HDTabBar.swift
//  HDSwfitWeibo
//
//  Created by wty on 16/4/8.
//  Copyright © 2016年 wty. All rights reserved.
//

import UIKit

class HDTabBar: UITabBar {
    //1.重新布局子控件
    override func layoutSubviews() {
         super.layoutSubviews()
        //重新布局所有tabBar所有子控件的frame
        //5.添加到父控件上
        self.addSubview(composeBtn)
        //宽度
        let  width = frame.size.width / CGFloat ( HDTabBarCount)
        //高度
        let height = frame.size.height
        
        //索引
        var index = 0
        //遍历tabbar子控件设置frame
        for subview in subviews {
            
            //如果是系统类型  就设置
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                subview.frame = CGRectMake( CGFloat ( index)*width, 0, width, height)
                //如果索引是1  就加2
                index += index == 1 ? 2 :1
            }
        }
        //设置中间按钮的frame
        composeBtn.frame = CGRectMake(2*width, 0, width, height)
        
    }
    //2.MARK 懒加载中间发布按钮
    //MARK -懒加中间按钮
    private lazy var composeBtn :UIButton  = {
        //1.创建按钮
        let btn  = UIButton ()
        //2.设置前景图片
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        //3.设置背景图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //4.添加监听
        btn.addTarget(self, action: Selector("composeBtnClick"), forControlEvents:UIControlEvents.TouchUpInside )
        
        //5.添加到父控件上
        self.addSubview(btn)
        return btn
        
    }()
    /**
     监听加号按钮点击
     注意: 监听按钮点击的方法不能是私有方法
     按钮点击事件的调用是由 运行循环 监听并且以消息机制传递的，因此，按钮监听函数不能设置为 private
     如果要加private  就是要
     */
    func composeBtnClick () {

         //modal控制器   由于是view 做不了 可以用代理或者闭包  获取
        //包装导航控制器
        let  controller = HDComposeController()
        UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(UINavigationController(rootViewController: controller), animated:  true  , completion: nil)
        
    }
}
